package mnfstedit

import (
	"strconv"
	"kumachan/standalone/qt"
	"kumachan/interpreter/compiler/loader/manifest"
)

type dependencyList struct {
	items    *([] manifest.Dependency)
	notify   func()
	current  int
}
func newDependencyList(items *([] manifest.Dependency), notify func()) *dependencyList {
	return &dependencyList {
		items:   items,
		notify:  notify,
		current: -1,
	}
}
func (l *dependencyList) SetCurrent(key string, exists bool) (manifest.Dependency, bool) {
	if exists {
		var i, err = strconv.Atoi(key)
		if err != nil { panic("something went wrong") }
		l.current = i
		return (*(l.items))[i], true
	} else {
		l.current = -1
		return manifest.Dependency {}, false
	}
}
func (l *dependencyList) TreeItems() ([] qt.TreeWidgetItem, *string) {
	var tree_items = make([] qt.TreeWidgetItem, len(*(l.items)))
	var current *string
	for i, dep := range *(l.items) {
		var key = strconv.Itoa(i)
		if i == l.current {
			current = &key
		}
		tree_items[i] = qt.TreeWidgetItem {
			Key:    key,
			Labels: [] string { dep.ImportName, dep.ModulePath },
		}
	}
	return tree_items, current
}
func (l *dependencyList) resetCurrent() {
	l.current = -1
}
func (l *dependencyList) mutate(f func()) ([] qt.TreeWidgetItem, *string) {
	f()
	l.notify()
	return l.TreeItems()
}
func (l *dependencyList) Append(item manifest.Dependency) ([] qt.TreeWidgetItem, *string) {
	return l.mutate(func() {
		l.current = len(*(l.items))
		*(l.items) = append(*(l.items), item)
	})
}
func (l *dependencyList) UpdateCurrent(f func(*manifest.Dependency)) ([] qt.TreeWidgetItem, *string) {
	return l.mutate(func() {
		f(&((*(l.items))[l.current]))
	})
}
func (l *dependencyList) RemoveCurrent() ([] qt.TreeWidgetItem, *string) {
	return l.mutate(func() {
		var cur = l.current
		if cur != -1 {
			var draft ([] manifest.Dependency)
			draft = append(draft, (*(l.items))[:cur]...)
			draft = append(draft, (*(l.items))[(cur+1):]...)
			*(l.items) = draft
			l.current = (cur - 1)
		}
	})
}
func (l *dependencyList) AdjustDownCurrent() ([] qt.TreeWidgetItem, *string) {
	return l.mutate(func() {
		var cur = l.current
		if cur != -1 && cur != (len(*(l.items)) - 1) {
			var draft = make([] manifest.Dependency, len(*(l.items)))
			copy(draft, *(l.items))
			draft[cur+1] = (*(l.items))[cur]
			draft[cur] = (*(l.items))[cur+1]
			*(l.items) = draft
			l.current = (cur + 1)
		}
	})
}
func (l *dependencyList) AdjustUpCurrent() ([] qt.TreeWidgetItem, *string) {
	return l.mutate(func() {
		var cur = l.current
		if cur != -1 && cur != 0 {
			var draft = make([] manifest.Dependency, len(*(l.items)))
			copy(draft, *(l.items))
			draft[cur-1] = (*(l.items))[cur]
			draft[cur] = (*(l.items))[cur-1]
			*(l.items) = draft
			l.current = (cur - 1)
		}
	})
}


